package auto

import (
	"fmt"
	"regexp"
	"sevlteServer/tool"
	"strings"
)

var Services = make(map[string]*tool.ServeEndPoint)

var rIsAPI = regexp.MustCompile(`(?i)^/api/(.*)?$`)

func AddService(ep *tool.ServeEndPoint) {
	for {
		if ep == nil {
			fmt.Println("ep is nil")
			break
		}

		if ep.Path == "" {
			fmt.Println("ep.path empty")
			break
		}

		if ep.Fn == nil {
			fmt.Println("must specify fn when ep.isFileServe equal false")
			break
		}

		if !rIsAPI.MatchString(ep.Path) {
			ep.Path = strings.ReplaceAll("/api/"+ep.Path, "//", "/")
		}

		if ep.Name == "" {
			fmt.Println("must specify apiName")
			break
		}
		_, ok := Services[ep.Path]
		if ok {
			fmt.Printf("%s[%s] already exists", ep.Path, ep.Name)
		}
		break
	}
	Services[ep.Path] = ep
	return
}
